package com.example.onedemotest.slice;

import com.example.onedemotest.ResourceTable;
import com.example.onedemotest.ServiceAbility;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.IAbilityConnection;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.DependentLayout;
import ohos.agp.window.dialog.ToastDialog;
import ohos.bundle.ElementName;
import ohos.data.DatabaseHelper;
import ohos.data.distributed.common.*;
import ohos.data.distributed.user.SingleKvStore;
import ohos.data.preferences.Preferences;
import ohos.data.rdb.*;
import ohos.data.resultset.ResultSet;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.rpc.IRemoteObject;
import ohos.utils.zson.ZSONObject;

import java.util.ArrayList;
import java.util.List;

public class SecondPageSlice extends AbilitySlice {

    private HiLogLabel hiLogLabel = new HiLogLabel(HiLog.LOG_APP, 0x101, "SecondPageSlice");

    private DependentLayout rootLayout;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        HiLog.info(hiLogLabel, "onStart");
        setUIContent(ResourceTable.Layout_activity_new_page);
        Button listDemoBtn = (Button) findComponentById(ResourceTable.Id_listDemo);
        Button tabListDemo = (Button) findComponentById(ResourceTable.Id_tabListDemo);
        Button pageSliderDemo = (Button) findComponentById(ResourceTable.Id_pageSliderDemo);
        Button customComponent = (Button) findComponentById(ResourceTable.Id_customComponent);
        Button adaptiveBoxBtn = (Button) findComponentById(ResourceTable.Id_adaptiveBoxBtn);
        Button notificationBtn = (Button) findComponentById(ResourceTable.Id_notificationBtn);
        Button serviceBtn = (Button) findComponentById(ResourceTable.Id_serviceBtn);
        Button serviceStopBtn = (Button) findComponentById(ResourceTable.Id_serviceStopBtn);
        Button saveDataBtn = (Button) findComponentById(ResourceTable.Id_saveDataBtn);
        Button getDataBtn = (Button) findComponentById(ResourceTable.Id_getDataBtn);
        listDemoBtn.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {

                Intent listIntent = new Intent();
                Operation operation = new Intent.OperationBuilder()
//                        .withAbilityName(ListSliceDemo.class.getName())
                        .withAction("action_list_demo")
                        .build();
                listIntent.setOperation(operation);
                startAbility(listIntent);

                //可以使用这个方法切换同一个page 之间的 slice 页面
                // present();
            }
        });

        tabListDemo.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {

//                Intent listIntent=new Intent();
//                Operation operation=new Intent.OperationBuilder()
////                        .withAbilityName(ListSliceDemo.class.getName())
//                        .withAction("action_list_demo")
//                        .build();
//                listIntent.setOperation(operation);
//                startAbility(listIntent);

                //可以使用这个方法切换同一个page 之间的 slice 页面
                // present();
                present(new TabListSlice(), new Intent());
            }
        });

        pageSliderDemo.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                present(new PageSliderSlice(), new Intent());
            }
        });

        customComponent.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                present(new CustomComponentSlice(), new Intent());
            }
        });
//        addButton();

        adaptiveBoxBtn.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                present(new AdaptiveBoxLayoutSlice(), new Intent());
            }
        });

        notificationBtn.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                present(new CommonEventSlice(), new Intent());
            }
        });

        serviceBtn.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
//                Operation operation=new Intent.OperationBuilder().withDeviceId("")
//                        .withBundleName(getBundleName())
//                        .withAbilityName(ServiceAbility.class.getName()).build();
//                Intent intentStart=new Intent();
//                intentStart.setOperation(operation);
//                startAbility(intentStart);
                testConnectService();
            }
        });

        serviceStopBtn.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
//                Operation operation=new Intent.OperationBuilder().withDeviceId("")
//                        .withBundleName(getBundleName())
//                        .withAbilityName(ServiceAbility.class.getName()).build();
//                Intent intentStart=new Intent();
//                intentStart.setOperation(operation);
//                stopAbility(intentStart);
                disconnectAbility(connection);
            }
        });

        saveDataBtn.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
//                saveData();
//                saveRDBData();
                saveKvStore();
            }
        });

        getDataBtn.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
//                getData();
//                getRDBData();
                getKvStore();
            }
        });
    }

    private void saveData() {
        DatabaseHelper databaseHelper = new DatabaseHelper(this);

        String fileName = "cache";
        Preferences preferences = databaseHelper.getPreferences(fileName);
        preferences.putString("userName", "xiaodu");
        //将 preferences 持久化
        preferences.flush();
    }

    //关系型数据库
    private void saveRDBData() {
        RdbStore rdbStore = createRdbStore();
        ValuesBucket valuesBucket = new ValuesBucket();
        valuesBucket.putString("userName", "hahahha");
        valuesBucket.putString("age", "20");
        long code = rdbStore.insert("test", valuesBucket);
        if (code == -1) {
            new ToastDialog(this).setText("插入失败").show();
        } else {
            new ToastDialog(this).setText("插入数据成功").show();
        }
        rdbStore.close();
    }

    private void getRDBData() {
        RdbStore rdbStore = createRdbStore();
        String[] columns = new String[]{"id", "userName", "age"};
        RdbPredicates predicates = new RdbPredicates("test").equalTo("age", "20");
        ResultSet resultSet = rdbStore.query(predicates, columns);
        if (resultSet == null) {
            new ToastDialog(this).setText("查询失败").show();
        } else {
            while (resultSet.goToNextRow()) {
                String userName = resultSet.getString(1);
                String age = resultSet.getString(2);
                new ToastDialog(this).setText(userName + age).show();
            }
        }
        rdbStore.close();
    }

    //分布式数据库存储
    private void saveKvStore() {
        SingleKvStore kvStore = createKVStore();
//        List<Entry> lists = new ArrayList<>();
//        lists.add(new Entry("userName", Value.get("小明")));
//        lists.add(new Entry("age", Value.get(20)));
//        kvStore.putBatch(lists);
        ZSONObject zsonObject = new ZSONObject();
        zsonObject.put("name", "消毒");
        zsonObject.put("age", 20);
        zsonObject.put("name", "小明");
        zsonObject.put("age", 20);
        zsonObject.put("name", "小王");
        zsonObject.put("age", 21);
        kvStore.putString("student", zsonObject.toString());
    }

    private void getKvStore() {
        SingleKvStore kvStore = createKVStore();
//        try {
//            String userName = kvStore.getString("userName");
//            new ToastDialog(this).setText(userName).show();
//        } catch (KvStoreException e) {
//            new ToastDialog(this).setText("查询失败").show();
//        }
        Query query = Query.select().equalTo("age", 20);
        List<Entry> entries = kvStore.getEntries(query);
        for (Entry entry : entries) {


            new ToastDialog(this).setText(entry.getKey() + entry.getValue()).show();
        }
    }


    //创建分布式数据库
    private SingleKvStore createKVStore() {
        KvManagerConfig config = new KvManagerConfig(this);
        KvManager kvManager = KvManagerFactory.getInstance().createKvManager(config);
        Options options = new Options();
        //单一分布式数据库
        options.setCreateIfMissing(true).setEncrypt(true).
                setBackup(true)
                .setAutoSync(true)
                .setKvStoreType(KvStoreType.SINGLE_VERSION)
                .setSchema(generateStudentSchema())
        ;
        SingleKvStore myStore = kvManager.getKvStore(options, "myStore");
        return myStore;
    }

    private Schema generateStudentSchema() {
        Schema schema = new Schema();
        //兼容模式
        schema.setSchemaMode(SchemaMode.COMPATIBLE);

        FieldNode nameNode = new FieldNode("name");
        schema.getRootFieldNode().appendChild(nameNode);
        FieldNode age = new FieldNode("age");
        schema.getRootFieldNode().appendChild(age);
        return schema;
    }

    private RdbStore createRdbStore() {
        DatabaseHelper databaseHelper = new DatabaseHelper(this);
        StoreConfig config = StoreConfig.newDefaultConfig("RDBTest.db");
        RdbOpenCallback rdbOpenCallback = new RdbOpenCallback() {

            @Override
            public void onCreate(RdbStore rdbStore) {
                rdbStore.executeSql("CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY AUTOINCREMENT, userName TEXT NOT NULL, age INTEGER, salary REAL, blobType BLOB)");
            }

            @Override
            public void onUpgrade(RdbStore rdbStore, int i, int i1) {

            }
        };
        RdbStore rdbStore = databaseHelper.getRdbStore(config, 1, rdbOpenCallback);
        return rdbStore;

    }


    private void getData() {
        DatabaseHelper databaseHelper = new DatabaseHelper(this);

        String fileName = "cache";
        Preferences preferences = databaseHelper.getPreferences(fileName);
        //将 preferences 持久化
//        preferences.flush();
        new ToastDialog(this).setText(preferences.getString("userName", "")).show();
    }

    private void testConnectService() {
        Operation Operation = new Intent.OperationBuilder().withDeviceId("")
                .withBundleName(getBundleName())
                .withAbilityName(ServiceAbility.class.getName())
                .build();
        Intent intent = new Intent();
        intent.setOperation(Operation);
        connectAbility(intent, connection);
    }

    private IAbilityConnection connection = new IAbilityConnection() {
        @Override
        public void onAbilityConnectDone(ElementName elementName, IRemoteObject iRemoteObject, int i) {
            ServiceAbility.MyLocalRemoteObject localRemoteObject = (ServiceAbility.MyLocalRemoteObject) iRemoteObject;

        }

        @Override
        public void onAbilityDisconnectDone(ElementName elementName, int i) {

        }
    };

    private void addButton() {
        Button button = new Button(this);
        button.setText("动态添加");
        rootLayout.addComponent(button);

    }

    @Override
    protected void onActive() {
        super.onActive();
        HiLog.info(hiLogLabel, "onActive");
    }

    @Override
    protected void onForeground(Intent intent) {
        super.onForeground(intent);
        HiLog.info(hiLogLabel, "onForeground");
    }

    @Override
    protected void onInactive() {
        super.onInactive();
        HiLog.info(hiLogLabel, "onInactive");
    }

    @Override
    protected void onBackground() {
        super.onBackground();
        HiLog.info(hiLogLabel, "onBackground");
    }

    @Override
    protected void onStop() {
        super.onStop();
        HiLog.info(hiLogLabel, "onStop");
    }

}
